//
//  FZUserSettingViewController.m
//  EnglishTalk
//
//  Created by CyonLeuMBP on 2017/2/21.
//  Copyright © 2017年 Feizhu Tech. All rights reserved.
//

#import "FZUserSettingViewController.h"
#import "FZUserSettingSectionModel.h"
#import "FZUserSettingModel.h"

#import "RIButtonItem.h"
#import "FZUserSettingTableViewCell.h"

#import "FZUserSettingConstant.h"
#import "SRLoginManager.h"
#import "SRCommonConstants.h"

#import "SRCommonWebViewController.h"
//#import "FZAgreementDeclareViewController.h"
#import "FZRegisterViewController.h"
#import "SRCellPhoneViewController.h"

#import "AppDelegate.h"
#import "UIAlertView+SRBlocks.h"

#import "FZMCCacheManager.h"
#import "SRModifyPasswordViewController.h"

@interface FZUserSettingViewController ()<UITableViewDataSource, UITableViewDelegate,  UIAlertViewDelegate,UIActionSheetDelegate>

@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *items;
@property (assign, nonatomic) BOOL onlyWIFIAutoPlay;
@property (strong, nonatomic) NSString *cacheSizeString;

@end

@implementation FZUserSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"设置";
    [self setupData];
    [self setupView];
    
    
    [self getUserSettingConfig];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - setup

- (void)setupData {
        //test data
    self.items = [@[] mutableCopy];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    if(![[[userDefaults dictionaryRepresentation] allKeys] containsObject:@"VideoAutoPlay"]){
        
        [userDefaults setBool:YES forKey:@"VideoAutoPlay"];
        [userDefaults synchronize];
    }
    
    if ([[userDefaults  objectForKey:@"VideoAutoPlay"]   boolValue])
    {
        self.onlyWIFIAutoPlay = YES;
    } else {
        self.onlyWIFIAutoPlay = NO;
    }
    [self refreshCacheSize];
}

- (void)setupView {
    
//    WEAKSELF
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 60;
    self.tableView.contentInset = UIEdgeInsetsMake(10, 0, 0, 0);
    
    [self.tableView registerNib:[UINib nibWithNibName:kFZUserSettingTableViewCell bundle:nil] forCellReuseIdentifier:kFZUserSettingTableViewCell];
    
    [self.view addSubview:self.tableView];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        //    self.tableView.separatorInset = UIEdgeInsetsMake(70, 70,0 , 0);
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.top.equalTo(self.view);
    }];
    self.tableView.backgroundColor = css.color_2;
}

- (void)getUserSettingConfig {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"UserSettingConfig" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    NSArray *sectionJSONArray = jsonDictionary[@"config_data"];
    NSArray *modelArray = [MTLJSONAdapter modelsOfClass:[FZUserSettingSectionModel class] fromJSONArray:sectionJSONArray error:nil];
    self.items = [modelArray mutableCopy];
    
    if (![SRLoginManager sharedManager].hasLogin) {
            //不显示退出登录
        
        for (int i = 0; i < [self.items count]; ++ i) {
            FZUserSettingSectionModel *sectionModel = self.items[i];
            if ([sectionModel.identifier isEqualToString:kUserSettingSectionAPNSPush]) {
                for (int j = 0; j < [sectionModel.cellModels count]; ++j) {
                    FZUserSettingModel *item = sectionModel.cellModels[j];
                    
                    if ([item.identifier isEqualToString:usersetting_changePwd]) {
                        NSMutableArray *models = [sectionModel.cellModels mutableCopy];
                        [models removeObjectAtIndex:j];
                        
                        sectionModel.cellModels = models;
                        break;
                    }
                }
            }
            else if ([sectionModel.identifier isEqualToString:kUserSettingSectionLogout]) {
                [self.items removeObjectAtIndex:i];
                break;
            }
        }
    }
    
    for (int i = 0; i < [self.items count]; ++ i) {
        FZUserSettingSectionModel *sectionModel = self.items[i];
        if ([sectionModel.identifier isEqualToString:kUserSettingSectionCommentApp]) {
            for (FZUserSettingModel *item in sectionModel.cellModels) {
                if ([item.identifier isEqualToString:usersetting_showVersion]) {
                    NSString *appVersion = [NSString  stringWithFormat:@"%@", APPVersion];// APPVersion];APPBuilderVersion
                    item.subtitle = appVersion;
                    break;
                }
            }
            break;
        }
    }
    
    [self.tableView reloadData];
}

- (void)refreshCacheSize {
    NSUInteger sdCacheSize = [[SDWebImageManager sharedManager].imageCache getSize];
    self.cacheSizeString = [NSString stringWithFormat:@"%.1f MB", sdCacheSize / (1024.0f * 1024.0f)];
    [self.tableView reloadData];
}

#pragma mark - Event

- (void)wifiAutoPlaySwitchAction:(BOOL)isOpen {
    self.onlyWIFIAutoPlay = isOpen;
    
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (isOpen) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"VideoAutoPlay"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        [MobClick event:@"me_setting" attributes:@{@"click":@"onlyWiFi"}];
        
        NSLog(@"只在WiFi下播放-开");
    }
    else {
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"VideoAutoPlay"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        NSLog(@"只在WiFi下播放-关");
        
    }
//    NSLog(@"VideoAutoPlayVideoAutoPlay %@",[defaults  objectForKey:@"VideoAutoPlay"]);
}

-(void)toJoinUsPage {
    [self startProgressHUD];
    WEAKSELF
    NSString *urlString = [[SRAPICreater sharedInstance] APIWithName:@"basic_html5"];
    [[SRNetWorkManager sharedInstance] GET:urlString needCache:NO parameters:nil responseClass:nil success:^(NSInteger statusCode, NSString *message, id dataObject) {
        [weakSelf stopProgressHUD];
        if (statusCode == kFZRequestStatusCodeSuccess) {
            
            SRCommonWebViewController *joinUs = [[SRCommonWebViewController alloc] init];
            joinUs.titleStr = @"加入我们";
            joinUs.needGoBack = YES;
            joinUs.urlString = dataObject[@"joinus_url"];
            [weakSelf.navigationController pushViewController:joinUs animated:YES];
        }
    } failure:^(id responseObject, NSError *error) {
        [weakSelf stopProgressHUD];
        [weakSelf showHUDError];
    }];
}

- (void)showWebVCWith:(NSString *)urlString title:(NSString *)title {
    SRCommonWebViewController *vc = [[SRCommonWebViewController alloc] init];
    vc.urlString = urlString;
    vc.titleStr = title;
    [self.navigationController pushViewController:vc animated:YES];
}



- (void)onAgreeButton:(id)sender {
        //协议
    FZBasicURLModel *urlModel = [SRLoginManager sharedManager].basicURLModel;
    if (urlModel && [urlModel.use_protocol length] > 0) {
        [self showWebVCWith:urlModel.use_protocol title:@"使用协议"];
    } else {
        WEAKSELF
        [self startProgressHUD];
        [[SRLoginManager sharedManager] queryBasicUrlWithSuccess:^(NSInteger statusCode, NSString *message, id responseDataObject) {
            [weakSelf stopProgressHUD];
            if (statusCode == kFZRequestStatusCodeSuccess) {
                FZBasicURLModel *model = responseDataObject;
                [weakSelf showWebVCWith:model.use_protocol title:@"使用协议"];
            } else {
                [weakSelf showHUDErrorMessage:message];
            }
        } failure:^(id responseObject, NSError *error) {
            [weakSelf stopProgressHUD];
            [weakSelf showHUDError];
        }];
        
    }
}

- (void)onAppRightsButton:(id)sender {
        //声明
    FZBasicURLModel *urlModel = [SRLoginManager sharedManager].basicURLModel;
    if (urlModel && [urlModel.copyright_url length] > 0) {
        [self showWebVCWith:urlModel.copyright_url title:@"版权声明"];
    } else {
        WEAKSELF
        [self startProgressHUD];
        [[SRLoginManager sharedManager] queryBasicUrlWithSuccess:^(NSInteger statusCode, NSString *message, id responseDataObject) {
            [weakSelf stopProgressHUD];
            if (statusCode == kFZRequestStatusCodeSuccess) {
                FZBasicURLModel *model = responseDataObject;
                [weakSelf showWebVCWith:model.copyright_url title:@"版权声明"];
            } else {
                [weakSelf showHUDErrorMessage:message];
            }
        } failure:^(id responseObject, NSError *error) {
            [weakSelf stopProgressHUD];
            [weakSelf showHUDError];
        }];
        
    }
}


- (void)toCleanCacheAction {
    
    WEAKSELF
    [[[UIAlertView alloc] initWithTitle:@""
                                message:@"确认清除缓存？"
                       cancelButtonItem:[RIButtonItem itemWithLabel:@"取消" action:^{
    }]
                       otherButtonItems:[RIButtonItem itemWithLabel:@"确认清除" action:^{
        STRONGSELFFor(weakSelf)
        [strongSelf startProgressHUD];
//        [[FZMCCacheManager defaultManager] removeAllBooks];
        [FZMCCacheManager removeUploadRecordCache];

        [[SDWebImageManager sharedManager].imageCache clearDiskOnCompletion:^{
            [strongSelf stopProgressHUD];
            [strongSelf showHUDHintWithText:@"清理缓存成功"];
            strongSelf.cacheSizeString = @"0MB";
            
            [strongSelf.tableView reloadData];
        }];
        
    }], nil] show];
    
    
}

- (void)toLogoutAction {
    [MobClick event:@"me_setting" attributes:@{@"click":@"exit"}];
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"确定要退出当前登录账号吗？" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"退出账号" otherButtonTitles:nil, nil];
    [actionSheet showInView:self.view];
}

- (void)toChangePassword {
    
    SRModifyPasswordViewController *vc = [[SRModifyPasswordViewController alloc] initWithNibName:@"SRModifyPasswordViewController" bundle:nil];    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)toBindPhone {
    FZRegisterViewController *vc = [[FZRegisterViewController alloc] init];
    vc.isBindPhone = YES;
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.items count];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    FZUserSettingSectionModel *sectionModel = self.items [section];
    if (sectionModel && sectionModel.cellModels) {
        return [sectionModel.cellModels count];
    }
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FZUserSettingTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:kFZUserSettingTableViewCell forIndexPath:indexPath];

    
//    NSInteger sectionCount = [self tableView:tableView numberOfRowsInSection:indexPath.section];
//    if (indexPath.row == (sectionCount - 1)) {
//            //最后一行隐藏分割线
//        cell.lineViewHidden = YES;
//    } else {
//        cell.lineViewHidden = NO;
//    }
    
    FZUserSettingSectionModel *sectionModel = self.items [indexPath.section];
    if ([sectionModel.cellModels count] > indexPath.row) {
        FZUserSettingModel *item = sectionModel.cellModels[indexPath.row];
        
        WEAKSELF
        if ([item.identifier isEqualToString:usersetting_WIFIAutoPlay]) {
            cell.settingSwitchHidden = NO;
            cell.titleTextAlignCenter = NO;
            cell.settingSwitch.on = self.onlyWIFIAutoPlay;
            
            cell.touchSettingSwitch = ^(BOOL isOpen) {
                [weakSelf wifiAutoPlaySwitchAction:isOpen];
            };
            
        }
        else  if ([item.identifier isEqualToString:usersetting_Logout]) {
            cell.titleTextAlignCenter = YES;
            cell.settingSwitchHidden = YES;
        }
        else  if ([item.identifier isEqualToString:usersetting_CleanCache]) {
            cell.titleTextAlignCenter = NO;
            cell.settingSwitchHidden = YES;
            item.subtitle = self.cacheSizeString;
        }
        else {
            cell.settingSwitchHidden = YES;
            cell.titleTextAlignCenter = NO;
        }
        
        [cell updateCellInfo:item];

    }

    return cell;
    
}

#pragma mark - UITableViewDelegate


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    FZUserSettingSectionModel *sectionModel = self.items [indexPath.section];
    if ([sectionModel.cellModels count] > indexPath.row) {
        FZUserSettingModel *item = sectionModel.cellModels[indexPath.row];
       if ([item.identifier isEqualToString:usersetting_AppRights]) {
                //版权声明
            [self onAppRightsButton:nil];
            
        }
        else if ([item.identifier isEqualToString:usersetting_UseProtocol]) {
                //版权声明
            [self onAgreeButton:nil];
        }
        else if ([item.identifier isEqualToString:usersetting_CommentApp]) {
                //好评一下
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:APPSTOREURL]];
        }
        else if ([item.identifier isEqualToString:usersetting_JoinUs]) {
                //加入我们
            [self toJoinUsPage];
        }
        else if ([item.identifier isEqualToString:usersetting_CleanCache]) {
                //清除缓存
            [self toCleanCacheAction];
        }
        else if ([item.identifier isEqualToString:usersetting_Logout]) {
                //退出登录
            [self toLogoutAction];
        }
        else if ([item.identifier isEqualToString:usersetting_changePwd]) {
            // 修改密码
            [self toChangePassword];
        }
        else if ([item.identifier isEqualToString:usersetting_BindPhone]) {
            // 绑定手机号
            [self toBindPhone];
        }
    }
    
}

#pragma mark - UIAcitonSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
            //退出登录
        [[SRLoginManager sharedManager] logout];
        
        [self logout];
        [self.navigationController popViewControllerAnimated:NO];
        [[NSNotificationCenter defaultCenter] postNotificationName:SRUserLogoutDoneNotification object:nil];
        
    }
    else if (buttonIndex == 1) {
            //取消
        
    }
}

-(void)logout {
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [delegate logoutAndRelogin:nil whetherEnterLoginVC:NO];
}


@end
